package cn.agiledata.bank.common.action;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.sql.Blob;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import cn.agiledata.bank.common.dao.AccountTemplateInter;
import cn.agiledata.bank.common.util.ImageUtil;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.common.util.WebUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.Information;
import cn.agiledata.bank.information.service.IInformationService;
import cn.agiledata.bank.myspace.service.IMySpaceService;
import com.vnv.infrastructure.action.IPBBaseAction;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class PhotoAction extends IPBBaseAction {
    private static final String CONTENT_TYPE = "image/jpeg";

    public int hasAccessPermission(int arg0, HttpServletRequest arg1)
            throws IPBException {
        // TODO Auto-generated method stub
        return 1;
    }

    protected IMySpaceService getMySpaceService() throws IPBException {
        return (IMySpaceService) IPBAppFactory.getObj(IMySpaceService.MGR_ID);
    }

    /**
     * 得到账户
     * 
     * @param request
     * @return
     */
    protected Account getAccount(HttpServletRequest request)
            throws IPBException {
        return getMySpaceService().getAccount(getAccountId(request));
    }

    /**
     * 得到账户Id
     * 
     * @param request
     * @return
     */
    protected String getAccountId(HttpServletRequest request)
            throws IPBException {
        String accountId = request.getParameter("accountId");
        if (StringUtil.isStrEmpty(accountId)) {
            accountId = String.valueOf(WeatherUtil
                    .getAccountIdFromSession(request));
        }
        return accountId;
    }

    /**
     * 
     * @param mapping
     * @param actionForm
     * @param request
     * @param response
     * @return
     * @throws IPBException
     * @throws Exception
     */
    public ActionForward showPhoto(ActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws IPBException, Exception {
        response.setContentType(CONTENT_TYPE);
        ServletOutputStream out = response.getOutputStream();
        InputStream ins = null;
        ins = getPhotoStream(request);
        String compressSize = request.getParameter("compressSize");
        if (compressSize == null) { // 不压缩
            int len;
            byte buf[] = new byte[4096];
            while ((len = ins.read(buf, 0, 4096)) != -1) {
                out.write(buf, 0, len);
            }
            ins.close();
            out.close();
            return mapping.findForward("photoBig");
        } else { // 压缩
            Image src = ImageIO.read(ins);
            ins.close();
            float tagsize = Float.parseFloat(compressSize);
            int old_w = src.getWidth(null);
            int old_h = src.getHeight(null);
            int new_w = 0;
            int new_h = 0;
            int tempsize;
            float tempdouble;
            if (old_w > old_h) {
                tempdouble = old_w / tagsize;
            } else {
                tempdouble = old_h / tagsize;
            }
            new_w = Math.round(old_w / tempdouble);
            new_h = Math.round(old_h / tempdouble);
            BufferedImage tag = new BufferedImage(new_w, new_h,
                    BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(src, 0, 0, new_w, new_h, null);
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(tag);

            out.close();
            return null;
        }

    }

    /**
     * 构造get方法
     * 
     * @param property
     * @return
     */
    public String parseGetMethod(String property) {
        String first = property.substring(0, 1);
        first = first.toUpperCase();
        String second = property.substring(1);
        return "get" + first + second;
    }

    /**
     * 得到数据库中的照片
     * 
     * @param request
     * @return
     */
    public InputStream getPhotoStream(HttpServletRequest request)
            throws Exception {
        Blob photo = null;

        Account account = getAccount(request);
        // String accountId = request.getParameter("accountId");
        AccountTemplateInter service = (AccountTemplateInter) IPBAppFactory
                .getObj("accountTemplate");
        // Account account = service.getAccount(accountId);
        String dbProperty = request.getParameter("dbProperty");
        String formProperty = request.getParameter("formProperty");
        if (formProperty != null) {
            formProperty = new String(formProperty.getBytes("iso-8859-1"),
                    "utf-8");
        }
        if (!StringUtil.isStrEmpty(dbProperty)) {
            Method method = account.getClass().getSuperclass()
                    .getDeclaredMethod(parseGetMethod(dbProperty), null);
            photo = (Blob) method.invoke(account, null);
            if (photo != null) {
                return photo.getBinaryStream();
            } else {
                FileInputStream defaultInputStream = new FileInputStream(
                        request.getRealPath("/images/noPhoto.gif"));
                return defaultInputStream;
            }
        }
        if (!StringUtil.isStrEmpty(formProperty)) {
            FileInputStream inputStream = new FileInputStream(formProperty);
            return inputStream;
        } else {
            FileInputStream defaultInputStream = new FileInputStream(request
                    .getRealPath("/images/noPhoto.gif"));
            return defaultInputStream;
        }
    }

    public ActionForward showInfoPic(ActionMapping mapping,
            ActionForm actionForm, HttpServletRequest request,
            HttpServletResponse response) throws IPBException, Exception {
        // InformationForm iform = (InformationForm)actionForm;
        IInformationService service = (IInformationService) IPBAppFactory
                .getObj("informationService");
        String id = request.getParameter("picId");
        Information information = service.getInformationById(id);
        response.setContentType(CONTENT_TYPE);
        ServletOutputStream out = response.getOutputStream();
        String compressSizeValue = request.getParameter("compressSize");
        double compressSize;
        try {
            compressSize = Double.parseDouble(compressSizeValue);
        } catch (Exception e) {
            compressSize = 0;
        }
        String defaultImageUri = WebUtil.getRoot(request)
                + "/images/noPhoto.gif";
        ImageUtil.blobImageToOutputStream(information.getPics(), out,
                compressSize, defaultImageUri);
        return null;
    }
}
